import os
from src.utils.tools import get_datetime
from src.db.db_history_rs_data_transform import insert_data_into_tables
from src.db.db_provider import DBProvider
from src.utils.tools import decompress
from src.utils.loghelper import logHelper


class HistoryRSDataTransform(object):

    def do_transform(self, file_path):
        files = os.listdir(file_path)

        logHelper.info("find %d files" % len(files))

        for file in files:
            if file.__contains__('LC'):
                landsat_history_rs_data_transformer = LandsatHistoryRSDataTransformer()
                landsat_history_rs_data_transformer.transform(file, file_path)

            if file.__contains__('.hdf'):
                modis_history_rs_data_transformer = MODISHistoryRSDataTransformer()
                modis_history_rs_data_transformer.transform(file, file_path)

            if file.__contains__('.hgt'):

                if file.__contains__('.zip'):
                    decompress("D:\AGROPrograms\AGRO\src\\temp\dem" + "\\" + file, "D:\AGROPrograms\AGRO\src\\temp\dem")

                dem_history_rs_data_transformer = DEMHistoryRSDataTransformer()
                dem_history_rs_data_transformer.transform(file, file_path)

            if file.__contains__('.grib'):
                ear5_history_rs_data_transformer = EAR5HistoryRSDataTransformer()
                ear5_history_rs_data_transformer.transform(file, file_path)

            if os.path.exists(file_path + "\\" + file):
                os.remove(file_path + "\\" + file)
                logHelper.info("file %s has been removed" % file)


class LandsatHistoryRSDataTransformer(object):

    _file_name_split_token = "_"

    """
    LC80180602015058LGN00_sr_band1 - 7.tiff
    如下：
    LC8 （代表Landsat第8号卫星） 018（卫星轨道path）060（卫星轨道row）2015058（2015
    年，从1月1日开始数的第58天）LGN00（这个可能是接收站的代号，不是很重要）
    _sr（反射率）_band1 - 7（波段1 - 7）.tiff
    """
    def transform(self, file_name, file_path):
        file_info_list = file_name.split(self._file_name_split_token)
        satellite_number = file_info_list[0][2:3]
        satellite_path = file_info_list[0][3:6]
        satellite_row = file_info_list[0][6:9]
        observation_year = file_info_list[0][9:13]
        observation_day_of_year = file_info_list[0][13:16]
        file_path = file_path + "\\" + file_name

        observation_date = get_datetime(int(observation_year), int(observation_day_of_year))

        data_type = file_info_list[1]
        data_band_range = file_info_list[2].split("-")
        data_band_least = data_band_range[0][4]
        data_band_most = data_band_range[1][0]

        # go to db
        execute_str = insert_data_into_tables['landsat'] % (
            int(satellite_number), int(satellite_path), int(satellite_row), "'" + observation_date + "'",
            int(observation_day_of_year),  "'" + data_type + "'", int(data_band_least), int(data_band_most),
            "'" + file_path + "'"
        )

        DBProvider().insert(execute_str)
        logHelper.info(execute_str)


class MODISHistoryRSDataTransformer(object):

    _file_name_split_token = "."

    """
    MOD13Q1.A2003001.h00v08.006.2015153201016

    MOD 代表 Terra
    MYD 代表 Aqua

    13Q1 代表 产品缩写
    A 代表 上午星   B 代表 下午星

    2003001 观测时间  2003年第1天

    h 横向 00
    v 纵向 08

    data_create_date 2015年第153天20：10：16
    """
    def transform(self, file_name, file_path):
        file_info_list = file_name.split(self._file_name_split_token)

        # satellite category
        satellite_category = None
        if file_info_list[0][0:3] == "MOD":
            # Terra
            satellite_category = "1"

        if file_info_list[0][0:3] == "MYD":
            # Aqua
            satellite_category = "0"

        product = file_info_list[0][3:7]

        observation_year = file_info_list[1][1:5]
        observation_day_of_year = file_info_list[1][5:8]

        horizontal = file_info_list[2][1:3]
        vertical = file_info_list[2][4:6]

        file_version = file_info_list[3]

        data_create_year = file_info_list[4][0:4]
        data_create_day_of_year = file_info_list[4][4:7]

        data_create_date = get_datetime(int(data_create_year), int(data_create_day_of_year)) + " " +(
            file_info_list[4][7:9] + ":" + file_info_list[4][9:11] + ":" + file_info_list[4][11:13])

        observation_date = get_datetime(int(observation_year), int(observation_day_of_year)) + " " + ("00:00:00")

        file_path = file_path + "\\" + file_name

        execute_str = insert_data_into_tables['modis'] % (
            int(satellite_category), "'" + product + "'", "'" + observation_date + "'",
            int(observation_day_of_year), int(horizontal), int(vertical),
            "'" + data_create_date + "'", "'" + file_path + "'", int(file_version)
        )

        DBProvider().insert(execute_str)
        logHelper.info(execute_str)


class DEMHistoryRSDataTransformer(object):

    _file_name_split_token = "."

    """
    N00E006.SRTMGL1.hgt.zip

    图像左下角 N00, E006

    L1 级别, 分辨率30m
    """

    def transform(self, file_name, file_path):
        file_info_list = file_name.split(self._file_name_split_token)

        data_location_latitude = file_info_list[0][1:3]
        data_location_longitude = file_info_list[0][4:7]

        data_latitude_type = file_info_list[0][0]
        data_longitude_type = file_info_list[0][3]

        data_level = file_info_list[1][-1]

        file_path = file_path + "\\" + file_name

        execute_str = insert_data_into_tables['dem'] % (
            int(data_location_latitude), int(data_location_longitude),
            "'" + data_latitude_type + "'", "'" + data_longitude_type + "'",
            "'" + data_level + "'", 30, "'" + file_path + "'"
        )

        DBProvider().insert(execute_str)
        logHelper.info(execute_str)


class EAR5HistoryRSDataTransformer(object):

    _file_name_split_token = "."

    def transform(self, file_name, file_path):
        file_info_list = file_name.split(self._file_name_split_token)[0].split("_")

        data_observation_date = file_info_list[0] + "-" + file_info_list[1] + "-" + file_info_list[2]

        file_path = file_path + "\\" + file_name

        execute_str = insert_data_into_tables['ear5'] % (
            "'" + data_observation_date + "'", "'" + file_path + "'"
        )

        DBProvider().insert(execute_str)
        logHelper.info(execute_str)





